<template>
	<div class="wly-page">
		<!--中间添加和查询条件-->
		<el-container>

			<div>
				<el-row>
					<el-col :span="24">
						<el-button type="text" icon="el-icon-plus" @click="userAddFormDialog">添加用户</el-button>
						<el-button type="text" icon="el-icon-d-caret" @click="handleThaw">正常/冻结</el-button>
					</el-col>
				</el-row>
				<div>
					<el-form ref="searchForm" :model="searchFormData" label-position="right" label-width="90px">
						<el-container>
							<el-row>
								<el-col :span="5">
									<el-form-item label="用户名：" prop="userNumber">
										<el-input v-model="searchFormData.username" placeholder="请输入用户名" size="mini" clearable></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item label="部门：" prop="depart">
										<el-input v-model="searchFormData.depart" placeholder="请输入部门" size="mini" clearable />
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item label="角色：" prop="role">
										<el-select v-model="searchFormData.role" clearable placeholder="请选择" size="mini">
											<el-option v-for="item in roleData" :key="item.roleId" :label="item.name" :value="item.roleId">
											</el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item label="状态：" prop="status">
										<el-select v-model="status" clearable placeholder="请选择" size="mini">
											<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
											</el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="4">
									<el-form-item label="">
										<AButton button-name="查询" icon="el-icon-search" @click="getUserList" size="mini"></AButton>
									</el-form-item>
								</el-col>
							</el-row>
						</el-container>
					</el-form>
				</div>
			</div>
		</el-container>
		<!--内容-->
		<ATable ref="table" :selectedData="selectedData" :tableData="tableData" :paramList="paramList" :height="tableHeight" :columns="columns"
			:recordNumber="recordNumber" :ifUseTableBase="ifUseTableBase" :ifUseTableButton="ifUseTableButton"
			:ifUseTableRodio="ifUseTableRodio" :ifUseTableOrder="ifUseTableOrder" @getData="getUserList" @handleEdit="handleEdit"
			@handleDelete="handleDelete" @getSelectRows="handleSelectionChange" @handleDetail="handleDetail">
		</ATable>

		<ADialogCom @closeDialog='closeDialog' :title="title" comName="UserForm" ref="ADialogCom"
			:dialog-open="dialogVisible2" @saved="getUserList"></ADialogCom>
		<el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
			<span>确认删除用户名为{{ username }}的记录</span>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="deleteUser">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import ajax from '@api/ajax'
import Treeselect from '@riophae/vue-treeselect'
import Msg from '@asst/js/msg'
import {
	QUERY_USER_INFO,
	USER_OPERATE,
	QUERY_DEP_INFO,
	QUERY_ROLE_INFO,
	USER_DELETE,
	USER_EDIT
} from '@api/url'
import AButton from '../../components/AInitPage/AUnitList/AButton'
export default {
	components: {
		AButton,
		Treeselect
	},
	data: () => ({
		ifUseTableButton: true,
		ifUseTableRodio: true,
		ifUseTableBase: true,
		ifUseTableOrder: false,
		isUseButton: true,
		selectedData: [],
		queryParam: {},
		tableData: [],
		recordNumber: 0,
		multipleSelection: [],
		height: window.innerHeight - 245,
		tableLoading: true,
		list: [{
			value: '删除',
			key: 'batchDel'
		}],
		searchFormData: {},
		options: [{
			value: '1',
			label: '冻结'
		}, {
			value: '0',
			label: '正常'
		}],
		status: '',
		input: '',
		pageInfo: {
			pageNo: 1,
			pageSize: 5,
			total: 0
		},
		search: {},
		tableRadio: {},
		roleNames: [],
		roleIds: [],
		curDate: '',
		usersLoading: false,
		codeMap: {
			status: {}
		},
		dialogVisible: false,
		dialogVisible2: false,
		username: '',
		deleteId: '',
		depData: [],
		roleData: [],
		// 表头
		columns: [{
			title: '用户名',
			dataIndex: 'username'
		},
		{
			title: '姓名',
			dataIndex: 'name'
		},
		{
			title: '部门名称',
			dataIndex: 'departName'
		},
		{
			title: '职务名称',
			dataIndex: 'postName'
		},
		{
			title: '角色',
			dataIndex: 'roleName'
		},
		{
			title: '邮箱',
			dataIndex: 'email'
		},
		{
			title: '手机',
			dataIndex: 'phone'

		},
		{
			title: '用户状态',
			dataIndex: 'status',
			ifTranslate: true,
		}

		],
		tableHeight: 0
	}),
	computed: {
		paramList() {
			return this.options.map(item => {
				return { type: 'status', code: item.value, value: item.label }
			})
		}
	},
	methods: {
		handleSelectionChange(val) {
			this.multipleSelection = val
		},
		normalizer(node) {
			return {
				id: node.departId,
				label: node.name,
				children: node.children
			}
		},
		// 重置
		resetForm() {
			this.searchFormData = ''
			this.status = ''
		},

		// 导航栏切换
		handleSelect(e) {
			if (e.index === '2') {
				this.$router.replace({
					path: '/home/user/OrganizationIndex'
				})
			}
			if (e.index === '3') {
				this.$router.replace({
					path: '/home/user/RoleIndex'
				})
			}
		},
		// 显示编辑界面
		handleEdit(row) {
			this.title = '用户编辑'
			this.dialogVisible2 = true
			this.$nextTick(() => {
				this.$refs.ADialogCom.aDialogComRef.UserForm.showUserDialog(row, 'edit')
			})
		},
		handleDetail(row) {
			this.title = '用户详情'
			this.dialogVisible2 = true
			this.$nextTick(() => {
				this.$refs.ADialogCom.aDialogComRef.UserForm.showUserDialog(row, 'detail')
			})
		},
		// 显示用户新增界面
		userAddFormDialog() {
			this.title = '用户新增'
			this.dialogVisible2 = true
			this.$nextTick(() => {
				this.$refs.ADialogCom.aDialogComRef.UserForm.showUserDialog({}, 'add')
			})
		},
		onClearSelected() {
			this.$refs.table.clearSelection()
		},
		// 点击删除按钮，将用户id存起来
		handleDelete(row) {
			Msg.confirm('是否删除该条数据？', {
				onConfirm: () => {
					this.username = row.username
					this.dialogVisible = true
					this.deleteId = row.userId
					let deleteConditions = {}
					deleteConditions.userId = this.deleteId
					deleteConditions.optMode = 'D'
					ajax.post(USER_OPERATE, deleteConditions).then(res => {
						this.$message.success('用户删除成功!')
						this.getUserList()
						this.dialogVisible = false
					}).catch(err => {
						console.error('用户列表查询错误！', err)
					})
				}
			})
			// this.username = row.username
			// this.dialogVisible = true
			// this.deleteId=row.userId
		},
		// 确认删除用户调用的方法
		deleteUser() {
			let deleteConditions = {}
			deleteConditions.userId = this.deleteId
			deleteConditions.optMode = 'D'
			ajax.post(USER_DELETE, deleteConditions).then(res => {
				this.$message.success('用户删除成功!')
				this.getUserList()
				this.dialogVisible = false
			}).catch(err => {
				console.error('用户列表查询错误！', err)
			})
		},
		// 列代码翻译
		columnFormatter(row, column) {
			let result = ''
			const columnName = column['property']
			switch (this.codeMap[columnName][row[columnName]] || row[columnName]) {
				case '0':
					result = '正常'
					break
				case '1':
					result = '冻结'
					break
			}
			return result
		},
		// 获取用户列表
		getUserList(data) {
			this.dialogVisible2 = false
			this.usersLoading = true
			// 搜索条件
			if (data != null && data.pageNo != null && data != undefined) {
				this.search.pageNo = data.pageNo
				this.search.pageSize = data.pageSize
			} else {
				this.search.pageNo = 1
				this.search.pageSize = 15
			}
			this.search.username = this.searchFormData.username
			this.search.depart = this.searchFormData.depart
			this.search.role = this.searchFormData.role
			this.search.status = this.status
			ajax.post(QUERY_USER_INFO, this.search).then(res => {
				// 总条数
				this.recordNumber = res.data.recordNumber
				// 数据
				let data = res.data.records
				this.tableData = data
				this.calHeight()
			}).catch(err => {
				console.error('用户列表查询错误！', err)
			}).finally(() => {
				this.usersLoading = false
				this.multipleSelection = []
			})
		},
		// 获取部门列表
		getDepList() {
			ajax.post(QUERY_DEP_INFO).then(res => {
				// 将数据处理成tree
				let tree = this.translateDataToTree(res.data)
				this.depData = tree
			}).catch(err => {
				console.error('查询发生错误！', err)
			}).finally(() => { })
		},
		// 获取角色列表
		getRoleList() {
			ajax.post(QUERY_ROLE_INFO).then(res => {
				this.roleData = res.data
			}).catch(err => {
				console.error('查询发生错误！', err)
			}).finally(() => { })
		},
		// 数据转换tree方法
		translateDataToTree(data) {
			// 没有父节点的数据
			let parents = data.filter(value => value.parentId === 'undefined' || value.parentId === '0')
			// 有父节点的数据
			let children = data.filter(value => value.parentId !== 'undefined' && value.parentId !== '0')
			// 定义转换方法的具体实现
			let translator = (parents, children) => {
				// 遍历父节点数据
				parents.forEach((parent) => {
					// 遍历子节点数据
					children.forEach((current, index) => {
						// 此时找到父节点对应的一个子节点
						if (current.parentId === parent.departId) {
							// 对子节点数据进行深复制，这里只支持部分类型的数据深复制，对深复制不了解的童靴可以先去了解下深复制
							let temp = JSON.parse(JSON.stringify(children))
							// 让当前子节点从temp中移除，temp作为新的子节点数据，这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
							temp.splice(index, 1)
							// 让当前子节点作为唯一的父节点，去递归查找其对应的子节点
							translator([current], temp)
							// 把找到子节点放入父节点的children属性中
							typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [
								current
							]
						}
					})
				})
			}
			// 调用转换方法
			translator(parents, children)
			// 返回最终的结果
			return parents
		},

		// 用户冻结解冻操作方法
		handleThaw(data) {
			// 1.获取选项
			var allSelectedData = this.multipleSelection
			if (allSelectedData.length > 0) {
				// var changStatusName = ''
				// 2.1判断当前状态,并改变
				for (var i in allSelectedData) {
					allSelectedData[i].optMode = "U"
					// 2.1如果(changStatus == 1(冻结))则将状态改为0(正常)
					if (allSelectedData[i].status == '1') {
						allSelectedData[i].status = '0'
						// changStatusName = '正常'
					} else if (allSelectedData[i].status == '0') {
						allSelectedData[i].status = '1'
						// changStatusName = '冻结'
					} else {
						this.$message.error('错误的标识!')
					}
				}
				debugger
				let arr = [];
				// 3. 请求后台
				allSelectedData.forEach(v => {
					arr.push(ajax.post(USER_OPERATE, v))
				})
				Promise.all(arr).then(res => {
					this.getUserList()
					this.$message.success('操作成功！')
				}).catch(err => {
					console.error(err, '操作失败!')
				})
			}
			// let changStatus=''
			// let changStatusName=''
			// if (data.status==='0'){
			//     changStatus='1'
			//     changStatusName='冻结'
			// }
			// if (data.status==='1'){
			//     changStatus='0'
			//     changStatusName='解冻'
			// }
			// this.$confirm('此操作将用户'+data.username+changStatusName+', 是否继续?', '提示', {
			//     confirmButtonText: '确定',
			//     cancelButtonText: '取消',
			//     type: 'warning'
			// }).then(() => {
			//     data.status=changStatus
			//     data.optMode='U'
			//     ajax.post(USER_OPERATE, data).then(res => {
			//         this.$message.success('操作成功!')
			//         this.getUserList()
			//     }).catch(err => {
			//         console.error('操作失败！', err)
			//     })
			// })
			},
			closeDialog() {
				this.dialogVisible2 = false
			},
			calHeight() {
				this.$nextTick(() => {
					this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 110
				})
			}
		},
		mounted() {
			this.getUserList()
			this.getDepList()
			this.getRoleList()
		}
	}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
	.el-form-item {
		// margin-left -30px
	}

	.disable-icon background-image url("../../images/icon/disable.png") .search_input width 200px height 45px .systemMenu {
		margin-left -20px
	}

	/*修改子菜单的背景色：*/
	.el-menu-item {
		border-radius: 0;
		background-color: white !important;
	}

	/*字体颜色：*/
	.el-aside {
		color: #f04959;
	}

	/*鼠标悬浮时，子菜单的样式：*/
	.el-menu-item:hover {
		border-radius: 0;
		outline: 0 !important;
		color: #409EFF !important;
	}

	.el-menu-item.is-active {
		color: white !important;
		background: #f04959 !important;
		border-radius: 0 !important;
	}

	/*鼠标悬浮时，主菜单的样式：*/
	.el-submenu__title:focus,
	.el-submenu__title:hover {
		outline: 0 !important;
		color: white !important;
		background: #f04959 !important;
	}

	.el-content-container {
		margin-top: 0
	}

	.el-alert {
		background-color: #e6f7ff;
		border: 1px solid #91d5ff;
	}

	.el-middle {
		margin-bottom: 20px
	}

	.adhoc /deep/ {
		.el-tabs__nav-wrap:after {
			display: none
		}

		.el-tabs__item {
			border-radius: 20px;
			padding: 0;
			padding-right: 20px !important;
			width: 100px;
			text-align: center;
		}

		.el-tabs__active-bar {
			background-color: #FFEBEB;
			height: 80%;
			top: 10%;
			border-radius: 20px;
			z-index: -1;
		}

		.el-menu-item.is-active {
			border-radius: 50px !important;
			overflow: hidden;
			box-shadow: none !important;
			background-color: #FFEBEB !important;
			color: #F95160 !important;
		}
	}
</style>
